package com.tebiecloud.act.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tebiecloud.act.client.model.entity.Act;
import com.tebiecloud.act.client.model.entity.ActCollect;
import com.tebiecloud.act.client.model.entity.ActGiftPack;
import com.tebiecloud.act.client.model.entity.ActGoodsRef;
import com.tebiecloud.act.client.model.vo.ActInfoVO;
import com.tebiecloud.act.client.model.vo.ActListVO;
import com.tebiecloud.act.client.model.vo.StoreVO;
import com.tebiecloud.act.server.mapper.ActCollectMapper;
import com.tebiecloud.act.server.mapper.ActGiftPackMapper;
import com.tebiecloud.act.server.mapper.ActGoodsRefMapper;
import com.tebiecloud.act.server.mapper.ActMapper;
import com.tebiecloud.act.server.service.ActService;
import com.tebiecloud.act.server.service.feign.GoodsServiceClient;
import com.tebiecloud.act.server.service.feign.StoreServiceClient;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.DateUtils;
import com.tebiecloud.common.utils.DistanceUtils;
import com.tebiecloud.goods.client.model.entity.Goods;
import com.tebiecloud.goods.client.model.entity.GoodsSpecification;
import com.tebiecloud.goods.client.model.vo.GoodsListVO;
import com.tebiecloud.store.client.model.entity.Store;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 活动表
 服务实现类
 * @author tebie
 * @date 2019-09-12
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class ActServiceImpl extends BaseServiceImpl<ActMapper, Act> implements ActService {

    @Autowired
    ActMapper actMapper;

    @Autowired
    ActGoodsRefMapper actGoodsRefMapper;

    @Autowired
    ActGiftPackMapper actGiftPackMapper;

    @Autowired
    ActCollectMapper actCollectMapper;

    @Autowired
    GoodsServiceClient goodsServiceClient;

    @Autowired
    StoreServiceClient storeServiceClient;

    @Override
    public  List<GoodsListVO> list(long storeId) {
        long nowTimestamp = System.currentTimeMillis();
        Date nowDate = new Date();
        QueryWrapper<Act> queryWrapper = new QueryWrapper<Act>();
        queryWrapper.eq("store_id",storeId);
        queryWrapper.eq("status",1);
        queryWrapper.eq("deleted",0);
        queryWrapper.eq("act_type",2);//体验活动
        queryWrapper.lt("shelf_time",nowDate);
        queryWrapper.gt("end_time",nowDate);
        List<Act> actList = actMapper.selectList(queryWrapper);
        List<GoodsListVO> goodsListVOList = new ArrayList<>();
        if(actList.size()>0){
                for(Act act:actList){
                Integer stockQty = 0; //库存数量
                Integer price = 0; //售价
                Integer purchaseStatus = 0; //购买状态：1即将开始，2抢购中，3已抢光，4已结束
                GoodsListVO goodsListVO = new GoodsListVO();
                goodsListVO.setActId(act.getActId());
                goodsListVO.setShelfTime(DateUtils.formatDate(act.getShelfTime(),"yyyy-MM-dd HH:mm:ss"));
                goodsListVO.setStartTime(DateUtils.formatDate(act.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
                goodsListVO.setEndTime(DateUtils.formatDate(act.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                //查询活动关联商品
                QueryWrapper<ActGoodsRef> goodsRefQueryWrapper = new QueryWrapper<>();
                goodsRefQueryWrapper.eq("act_id",act.getActId());
                goodsRefQueryWrapper.eq("deleted",0);
                List<ActGoodsRef> actGoodsRefList = actGoodsRefMapper.selectList(goodsRefQueryWrapper);
                if(actGoodsRefList.size()>0){
                    long specId = 0;
                    for(int i =  0;i<actGoodsRefList.size();i++){
                        if(i==0){
                            price = actGoodsRefList.get(0).getPrice();
                            specId = actGoodsRefList.get(0).getSpecId();
                        }
                        if(actGoodsRefList.get(i).getPrice()<price){
                            specId = actGoodsRefList.get(i).getSpecId();
                        }
                        String goodsIds = actGoodsRefList.get(i).getGoodsId().toString();
                        goodsListVO.setGoodsId(actGoodsRefList.get(i).getGoodsId());
                        //获取规格信息
                        ResultBody<List<GoodsSpecification>> goodsSpecResultBody = goodsServiceClient.selectBySpecIds(String.valueOf(specId));
                        if(goodsSpecResultBody!=null && goodsSpecResultBody.getCode() == ResultEnum.OK.getCode()){
                            List<GoodsSpecification> goodsSpecificationList = goodsSpecResultBody.getData();
                            goodsListVO.setSpecName(goodsSpecificationList.get(0).getName());
                        }
                        //获取商品信息
                        ResultBody<List<Goods>> goodsResultBody = goodsServiceClient.selectByGoodsIds(goodsIds);
                        List<Goods> goodsList = null;
                        if(goodsResultBody!=null && goodsResultBody.getCode() == ResultEnum.OK.getCode()){
                            goodsList = goodsResultBody.getData();
                            if(goodsList!=null){
                                goodsListVO.setGoodsName(goodsList.get(0).getName());
                                goodsListVO.setGoodsType(goodsList.get(0).getGoodsType());
                                goodsListVO.setMainPic(goodsList.get(0).getMainPic());
                            }
                        }
                    }
                }
                QueryWrapper<ActGiftPack> giftPackQueryWrapper = new QueryWrapper<>();
                giftPackQueryWrapper.eq("activity_id",act.getActId());
                ActGiftPack actGiftPack = actGiftPackMapper.selectOne(giftPackQueryWrapper);
                if(actGiftPack!=null){
                    goodsListVO.setPrice(actGiftPack.getPrice());
                    goodsListVO.setRetailPrice(actGiftPack.getRetailPrice());
                    stockQty = actGiftPack.getStockQty();
                }
                //判断购买状态
                if(nowTimestamp>=act.getShelfTime().getTime()&&nowTimestamp<=act.getShelfTime().getTime()){
                    purchaseStatus = 1;
                }
                if(nowTimestamp>=act.getStartTime().getTime()&&nowTimestamp<=act.getEndTime().getTime()){
                    purchaseStatus = 2;
                }
                if(stockQty<=0){
                    purchaseStatus = 3;
                }
                if(nowTimestamp>=act.getEndTime().getTime()){
                    purchaseStatus = 4;
                }
                goodsListVO.setPurchaseStatus(purchaseStatus);
                goodsListVOList.add(goodsListVO);
            }
        }
        return goodsListVOList;
    }

    @Override
    public ActInfoVO getActVO(long actId, Double lng, Double lat) {
        long nowTimestamp = System.currentTimeMillis();
        Act act = actMapper.selectById(actId);
        ActInfoVO actVO = new ActInfoVO();
        Integer stockQty = 0; //库存数量
        Integer benefit = 0; //赚多少
        Integer purchaseStatus = 0; //购买状态：1即将开始，2抢购中，3已抢光，4已结束
        String distance = "0m"; //距离
        actVO.setActId(act.getActId());
        actVO.setActName(act.getName());
        actVO.setSharePic(act.getSharePic());
        actVO.setShareTitle(act.getShareTitle());
        actVO.setShareRemark(act.getShareRemark());
        actVO.setShelfTime(DateUtils.formatDate(act.getShelfTime(),"yyyy-MM-dd HH:mm:ss"));
        actVO.setStartTime(DateUtils.formatDate(act.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
        actVO.setEndTime(DateUtils.formatDate(act.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        //查询活动关联商品
        QueryWrapper<ActGoodsRef> goodsRefQueryWrapper = new QueryWrapper<ActGoodsRef>();
        goodsRefQueryWrapper.eq("act_id",actId);
        goodsRefQueryWrapper.eq("deleted",0);
        List<ActGoodsRef> actGoodsRefList = actGoodsRefMapper.selectList(goodsRefQueryWrapper);
        if(actGoodsRefList.size()>0){
            List<GoodsListVO> goodsListVOS = new ArrayList<GoodsListVO>();
            for(int i =  0;i<actGoodsRefList.size();i++){
                stockQty = stockQty + actGoodsRefList.get(i).getStockQty();
                String goodsIds = actGoodsRefList.get(i).getGoodsId().toString();
                //获取商品信息
                ResultBody<List<Goods>> goodsResultBody = goodsServiceClient.selectByGoodsIds(goodsIds);
                List<Goods> goodsList = null;
                if(goodsResultBody!=null && goodsResultBody.getCode() == ResultEnum.OK.getCode()){
                    goodsList = goodsResultBody.getData();
                }
                if(goodsList!=null && goodsList.size()>0){
                    GoodsListVO goodsListVO = new GoodsListVO();
                    //获取规格
                    String specIds = actGoodsRefList.get(i).getSpecId().toString();
                    ResultBody<List<GoodsSpecification>> goodsSpecificationResultBody = goodsServiceClient.selectBySpecIds(specIds);
                    List<GoodsSpecification> goodsSpecifications = null;
                    if(goodsSpecificationResultBody!=null && goodsSpecificationResultBody.getCode() == ResultEnum.OK.getCode()){
                        goodsSpecifications  = goodsSpecificationResultBody.getData();
                    }
                    goodsListVO.setGoodsId(actGoodsRefList.get(i).getGoodsId());
                    goodsListVO.setGoodsName(goodsList.get(0).getName());

                    if(goodsSpecifications!=null && goodsSpecifications.size()>0)
                    goodsListVO.setSpecName(goodsSpecifications.get(0).getName());

                    String[] carouselPics = goodsList.get(0).getCarouselPics().split(",");
                    String[] detailPics = goodsList.get(0).getDetailPics().split(",");
                    actVO.setCarouselPics(Arrays.asList(carouselPics));
                    actVO.setDetailPics(Arrays.asList(detailPics));

                    goodsListVO.setPrice(actGoodsRefList.get(i).getPrice());
                    goodsListVO.setRetailPrice(actGoodsRefList.get(i).getRetailPrice());
                    goodsListVOS.add(goodsListVO);
                    String storeIds = goodsList.get(0).getStoreId().toString();
                    //获取门店信息
                    ResultBody<List<Store>> storeResultBody = storeServiceClient.selectStoreList(storeIds);
                    if(storeResultBody!=null && storeResultBody.getCode() == ResultEnum.OK.getCode()){
                        List<Store> storeList = storeResultBody.getData();
                        StoreVO storeVO = new StoreVO();
                        //计算距离
                        if(storeList!=null && storeList.size()>0){
                            storeVO.setStoreName(storeList.get(0).getName());
                            storeVO.setAddress(storeList.get(0).getAddress());
                            storeVO.setLng(storeList.get(0).getLng());
                            storeVO.setLat(storeList.get(0).getLat());
                            actVO.setStore(storeVO);
                            if(lat!=null&&lng!=null){
                                distance = DistanceUtils.getDistance(lng,lat,storeList.get(0).getLng(),storeList.get(0).getLat());
                                actVO.setDistance(distance);
                            }
                        }
                    }
                }
            }
        }
        //获取收藏列表
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        if(securityUserDetails!=null){
            QueryWrapper<ActCollect> actCollectQueryWrapper = new QueryWrapper<ActCollect>();
            actCollectQueryWrapper.eq("user_id", securityUserDetails.getUserId());
            actCollectQueryWrapper.eq("act_id",actId);
            List<ActCollect> actCollectList =  actCollectMapper.selectList(actCollectQueryWrapper);
            if(actCollectList!=null && actCollectList.size()>0){
                actVO.setIsCollect(1); //已收藏
            }else{
                actVO.setIsCollect(0); //未收藏
            }
        }

        //判断购买状态
        if(nowTimestamp>=act.getShelfTime().getTime()&&nowTimestamp<=act.getShelfTime().getTime()){
            purchaseStatus = 1;
        }
        if(nowTimestamp>=act.getStartTime().getTime()&&nowTimestamp<=act.getEndTime().getTime()){
            purchaseStatus = 2;
        }
        if(stockQty<=0){
            purchaseStatus = 3;
        }
        if(nowTimestamp>=act.getEndTime().getTime()){
            purchaseStatus = 4;
        }
        actVO.setPurchaseStatus(purchaseStatus);
        return actVO;
    }

    @Override
    public ActListVO selectActByActIdAndGoodsId(long actId, long goodsId) {
        long nowTimestamp = System.currentTimeMillis();
        QueryWrapper<Act> queryWrapper = new QueryWrapper<Act>();
        queryWrapper.eq("act_id",actId);
        Act act = actMapper.selectOne(queryWrapper);
        Integer stockQty = 0; //库存数量
        Integer price = 0; //售价
        Integer retailPrice = 0; //门市价
        Integer purchaseStatus = 1; //购买状态：1即将开始，2抢购中，3已抢光，4已结束
        ActListVO actListVO = new ActListVO();
        actListVO.setActId(act.getActId());
        actListVO.setActType(act.getActType());
        actListVO.setSharePic(act.getSharePic());
        actListVO.setShareTitle(act.getShareTitle());
        actListVO.setShareRemark(act.getShareRemark());
        actListVO.setIsRefundable(act.getIsRefundable());
        String[] carouselPics = act.getCarouselPics().split(",");
        String[] detailPics = act.getDetailPics().split(",");
        actListVO.setCarouselPics(Arrays.asList(carouselPics));
        actListVO.setDetailPics(Arrays.asList(detailPics));
        actListVO.setShelfTime(DateUtils.formatDate(act.getShelfTime(),"yyyy-MM-dd HH:mm:ss"));
        actListVO.setStartTime(DateUtils.formatDate(act.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
        actListVO.setEndTime(DateUtils.formatDate(act.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        //查询活动关联商品
        QueryWrapper<ActGoodsRef> goodsRefQueryWrapper = new QueryWrapper<ActGoodsRef>();
        goodsRefQueryWrapper.eq("act_id",act.getActId());
        goodsRefQueryWrapper.eq("goods_id",goodsId);
        goodsRefQueryWrapper.eq("deleted",0);
        List<ActGoodsRef> actGoodsRefList = actGoodsRefMapper.selectList(goodsRefQueryWrapper);
        if(actGoodsRefList.size()>0){
            long specId = 0;
            for(int i =  0;i<actGoodsRefList.size();i++){
                if(i==0){
                    price = actGoodsRefList.get(0).getPrice();
                    specId = actGoodsRefList.get(0).getSpecId();
                    retailPrice = actGoodsRefList.get(0).getRetailPrice();
                }
                stockQty = stockQty + actGoodsRefList.get(i).getStockQty();
                if(actGoodsRefList.get(i).getPrice()<price){
                    price = actGoodsRefList.get(i).getPrice();
                    retailPrice = actGoodsRefList.get(i).getRetailPrice();
                    specId = actGoodsRefList.get(i).getSpecId();
                }
            }
            String goodsIds = actGoodsRefList.get(0).getGoodsId().toString();
            ResultBody<List<Goods>>  goodsResultBody = goodsServiceClient.selectByGoodsIds(goodsIds);
            if(goodsResultBody!=null && goodsResultBody.getCode() == ResultEnum.OK.getCode()){
                List<Goods> goodsList = goodsResultBody.getData();
                if(goodsList!=null && goodsList.size()>0){
                    actListVO.setActName(goodsList.get(0).getName());
                    actListVO.setMainPic(goodsList.get(0).getMainPic());
                }
            }
            //获取规格信息
            ResultBody<List<GoodsSpecification>> goodsSpecResultBody = goodsServiceClient.selectBySpecIds(String.valueOf(specId));
            if(goodsSpecResultBody!=null && goodsSpecResultBody.getCode() == ResultEnum.OK.getCode()){
                List<GoodsSpecification> goodsSpecificationList = goodsSpecResultBody.getData();
                actListVO.setSpecName(goodsSpecificationList.get(0).getName());
            }else {
                log.info(">>minjie 查询规格出错");
            }
        }else {
            log.info(">>minjie 查询没有活动");
        }
        actListVO.setPrice(price);
        actListVO.setRetailPrice(retailPrice);
        //判断购买状态
        if(nowTimestamp>=act.getShelfTime().getTime() && nowTimestamp<act.getStartTime().getTime()){
            actListVO.setRemainTime((act.getStartTime().getTime() - nowTimestamp)/1000);//距离开抢时间还剩多少秒，单位：秒
            purchaseStatus = 1;
        }
        if(nowTimestamp>=act.getStartTime().getTime()&&nowTimestamp<act.getEndTime().getTime()){
            actListVO.setRemainTime((act.getEndTime().getTime() - nowTimestamp)/1000);//距离开抢时间还剩多少秒，单位：秒
            purchaseStatus = 2;
        }
        if(stockQty<=0){
            purchaseStatus = 3;
        }
        if(nowTimestamp>=act.getEndTime().getTime()){
            purchaseStatus = 4;
        }
        actListVO.setPurchaseStatus(purchaseStatus);
        return actListVO;
    }
}
